package com.xingmang.common.utils;

import com.xingmang.common.constant.CommonProperties;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @auther: hansom
 * @Version: 1.0
 * @create 2023/4/21 9:42
 */
public class FileUtils {
    public static Map<String,Object> upload(MultipartFile file, HttpServletRequest req){
        Map<String,Object> map = new HashMap<>();
        File folder = new File(CommonProperties.BASE_FOLDER_PATH);
        String filePath = "";
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() +
                oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            file.transferTo(new File(folder, newName));
            filePath = "http://wzcsdx-api.yhmhzq.top/upload/" + newName;

//            map.put("url","http://localhost:8089/info/downLoad");
            map.put("url",filePath);
            map.put("fileName",newName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    public String fileToBase64(MultipartFile file) throws IOException{
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(file.getBytes());
        return encode;
    }
}
